<template>
  <div class="app-container">
    <SearchWithOperate
      :form-options="formOptions"
      btn-items="add,import,export"
      @onSearch="handleQuery"
      @onAdd="handleAdd"
      @onImport="handleImport"
      @onExport="handleExport"
    >
      <template v-slot:otherBtn>
        <el-tooltip
          v-if="isExpandAll"
          :open-delay="600"
          content="折叠全部"
          placement="bottom"
        >
          <el-button
            class="operate"
            type="primary"
            plain
            icon="iconfont icon-tool-collapse"
            size="mini"
            @click="toggleExpandAll"
          />
        </el-tooltip>
        <el-tooltip
          v-else
          :open-delay="600"
          content="展开全部"
          placement="bottom"
        >
          <el-button
            class="operate"
            type="primary"
            plain
            icon="iconfont icon-tool-expand"
            size="mini"
            @click="toggleExpandAll"
          />
        </el-tooltip>
      </template>
    </SearchWithOperate>

    <el-table
      v-if="refreshTable"
      :loading="loading"
      class="table-padding"
      tooltip-effect="light"
      :data="deptList"
      row-key="deptId"
      :default-expand-all="isExpandAll"
      border
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="deptName" label="部门名称" />
      <el-table-column
        prop="deptCode"
        label="部门编码"
        align="center"
      />
      <el-table-column prop="orderNum" label="排序" width="70" align="center" />
      <el-table-column prop="status" label="状态" width="70" align="center">
        <template slot-scope="scope">
          <span class="stateShell">
            <div
              v-if="scope.row.status === '0'"
              class="common-prompt"
              style="background-color: #67c23a"
            />
            <div
              v-else
              class="common-prompt"
              style="background-color: #f56c6c"
            />
            <dict-tag
              :options="dict.type.status"
              :value="scope.row.status"
            /> </span></template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        width="180"
        prop="createTime"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="300"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['system:dept:edit']"
            size="mini"
            type="primary"
            plain
            style="margin-right: 10px"
            @click="handleUpdate(scope.row)"
          >编辑</el-button>
          <el-button
            v-hasPermi="['system:dept:add']"
            size="mini"
            type="primary"
            plain
            style="margin-right: 10px"
            @click="handleAdd(scope.row)"
          >添加</el-button>
          <el-button
            v-if="
              scope.row.parentId !== 0 ||
                (scope.row.parentId === 0 && scope.row.children.length === 0)
            "
            v-hasPermi="['system:dept:remove']"
            size="mini"
            type="danger"
            plain
            style="margin-left: 10px"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改部门对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="60"
      append-to-body
      class="dept-dialog"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col v-if="form.parentId !== 0" :span="24">
            <el-form-item label="上级部门" prop="parentId">
              <treeselect
                v-model="form.parentId"
                :options="deptOptions"
                :normalizer="normalizer"
                no-options-text="暂无数据"
                no-results-text="暂无数据"
                no-children-text="暂无数据"
                placeholder="选择上级部门"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="部门编码" prop="deptCode">
              <el-input v-model="form.deptCode" placeholder="请输入部门编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门名称" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入部门名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="组织类型" prop="orgType">
              <el-select
                v-if="!form.parentId || form.parentId === 0"
                v-model="form.orgType"
                placeholder="请选择组织类型"
                clearable
              >
                <el-option
                  v-for="dict in orgTypeDicts"
                  :key="dict.value"
                  :label="dict.label"
                  :value="Number(dict.value)"
                />
              </el-select>
              <span v-else>{{ renderOrgTypeByDeptId(form.parentId) }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-input
                v-model="form.leader"
                placeholder="请输入负责人"
                maxlength="20"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input
                v-model="form.phone"
                placeholder="请输入联系电话"
                maxlength="11"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="form.email"
                placeholder="请输入邮箱"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number
                v-model="form.orderNum"
                controls-position="right"
                :min="0"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          :loading="submitLoading"
          @click="submitForm"
        >确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 部门导入 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-change="handleFileChange"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip text-center">
          <div slot="tip" class="el-upload__tip">
            <el-checkbox v-model="upload.updateSupport" />
            是否更新已经存在的部门数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
          >下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listDept,
  getDept,
  delDept,
  addDept,
  updateDept,
  listDeptExcludeChild
} from '@/api/system/dept'
import { getToken } from '@/utils/auth'

import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'Dept',
  dicts: ['sys_normal_disable', 'orgType', 'status'],
  components: { Treeselect },
  data() {
    return {
      // 上传文件标志
      isFile: false,
      importLoading: false,
      // 遮罩层
      loading: true,
      submitLoading: false,
      // 表格树数据
      deptList: [],
      // 部门树选项
      deptOptions: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        deptName: undefined,
        status: undefined,
        deptCode: '',
        orgType: undefined,
        delFlag: 0
      },
      // 部门导入参数
      upload: {
        // 是否显示弹出层（部门导入）
        open: false,
        // 弹出层标题（部门导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的部门数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/system/dept/importData'
      },
      // 表单参数
      form: {},
      divisionCodes: [],
      // 表单校验
      rules: {
        deptName: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' }
        ],
        orgType: [
          { required: true, message: '组织类型不能为空', trigger: 'change' }
        ],
        orderNum: [
          { required: true, message: '显示排序不能为空', trigger: 'blur' }
        ],
        email: [
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ],
        phone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ],
        deptCode: {
          required: true,
          message: '部门编码不能为空',
          trigger: 'blur'
        }
      },
      adminDivisions: [],
      orgTypeMap: {},
      devisionParentsMap: {},
      // 查询条件
      formOptions: [
        {
          label: '部门编码:',
          prop: 'deptCode',
          type: 'input',
          placeholder: '请输入部门编码'
        },
        {
          label: '部门名称:',
          prop: 'deptName',
          type: 'input',
          placeholder: '请输入部门名称'
        },
        {
          label: '组织类型:',
          prop: 'orgType',
          type: 'select',
          options: [],
          placeholder: '请选择组织类型'
        },
        {
          label: '状态:',
          prop: 'status',
          type: 'select',
          options: [],
          placeholder: '部门状态'
        }
      ]
    }
  },
  computed: {
    orgTypeDicts() {
      const result = []
      const dictData = this.dict
      if (dictData && dictData.type && dictData.type.orgType) {
        dictData.type.orgType.forEach((item) => {
          this.orgTypeMap[item.value] = item
          result.push(item)
        })
      }
      return result
    },
    deptMap() {
      const result = {}
      if (this.deptList && this.deptList.length > 0) {
        this.listToMapData(this.deptList, result, 'deptId')
      }
      return result
    }
  },
  created() {
    // TODO 加载区划数据
    this.getList()
  },
  mounted() {
    this.formOptions[2].options = this.dict.type.orgType
    this.formOptions[3].options = this.dict.type.sys_normal_disable
  },
  methods: {
    // 提交上传文件
    submitFileForm() {
      if (this.isFile) {
        this.$refs.upload.submit()
      } else {
        this.$message.warning('请选择上传文件')
      }
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          '</div>',
        '导入结果',
        { dangerouslyUseHTMLString: true }
      )
      this.getList()
    },
    // 文件上传发生变化时调用
    handleFileChange(response, file, fileList) {
      if (file.length !== 0) {
        this.isFile = true
        const type = file[0].raw.type
        if (
          type !==
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' &&
          type !== 'application/vnd.ms-excel'
        ) {
          this.$message.error('上传的文件类型错误')
          this.isFile = false
          this.$refs.upload.clearFiles()
        }
      }
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        'system/dept/importTemplate',
        {},
        `dept_template_${new Date().getTime()}.xlsx`
      )
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'system/dept/export',
        {
          ...this.queryParams
        },
        `dept_${new Date().getTime()}.xlsx`
      )
    },
    /** 导入按钮操作 */
    handleImport() {
      this.importLoading = false
      this.isFile = false
      this.upload.title = '部门导入'
      this.upload.open = true
    },
    /**
     * 加载区划数据
     */
    loadDivisionList() {

    },
    /** 查询部门列表 */
    getList() {
      this.loading = true
      listDept(this.queryParams).then((response) => {
        this.deptList = this.handleTree(response.data, 'deptId')
        this.loading = false
      })
    },
    listToMapData(list, map, key, childrenKey) {
      const tmpChildrenKey = childrenKey || 'children'
      if (list && list.length > 0) {
        list.forEach((item) => {
          map[item[key]] = item
          this.listToMapData(item[tmpChildrenKey] || [], map, key, childrenKey)
        })
      }
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.deptId || node.id,
        label: node.deptName || node.label,
        children: node.children
      }
    },
    /** 转换区划数据结构 */
    normalizerDivision(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.divisionCode || node.id,
        label: node.divisionName || node.label,
        children: node.children
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        deptId: undefined,
        parentId: undefined,
        deptCode: undefined,
        deptName: undefined,
        orderNum: 0,
        leader: undefined,
        phone: undefined,
        email: undefined,
        status: '0',
        orgType: undefined,
        divisionCode: undefined
      }
      this.divisionCodes = []
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery(data) {
      this.queryParams = Object.assign(this.queryParams, data)
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset()
      this.submitLoading = false
      if (row !== null && row !== undefined) {
        this.form.parentId = row.deptId
        this.form.orgType = row.orgType
      }
      this.open = true
      this.title = '添加部门'
      listDept().then((response) => {
        this.deptOptions = this.handleTree(response.data, 'deptId')
      })
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false
      this.isExpandAll = !this.isExpandAll
      this.$nextTick(() => {
        this.refreshTable = true
      })
    },
    // 部门状态修改
    handleStatusChange(row) {
      const text = row.status === '0' ? '启用' : '停用'
      this.$modal
        .confirm('确认要"' + text + '""' + row.deptName + '"吗？')
        .then(function() {
          return updateDept(row)
        })
        .then(() => {
          this.$modal.msgSuccess(text + '成功')
          this.getList()
        })
        .catch(function() {
          row.status = row.status === '0' ? '1' : '0'
        })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.submitLoading = false
      getDept(row.deptId).then((response) => {
        this.form = response.data
        if (this.form.orgType === -1) {
          this.form.orgType = null
        }
        if (this.form.orgType === null || this.form.orgType === undefined) {
          if (this.deptMap[this.form.parentId]) {
            this.form.orgType = this.deptMap[this.form.parentId].orgType
          }
        }
        this.open = true
        this.title = '修改部门'
        this.initDeptDivisionCode(this.form.divisionCode)
      })
      listDeptExcludeChild(row.deptId).then((response) => {
        this.deptOptions = this.handleTree(response.data, 'deptId')
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.submitLoading = true
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.divisionCodes.length > 0) {
            this.form.divisionCode =
              this.divisionCodes[this.divisionCodes.length - 1]
          }
          if (this.form.deptId !== null && this.form.deptId !== undefined) {
            updateDept(this.form)
              .then((response) => {
                this.$modal.msgSuccess('修改成功')
                this.open = false
                this.getList()
              })
              .catch((err) => {
                this.submitLoading = false
                console.error(err)
              })
          } else {
            const paramData = { ...this.form }
            if (paramData.orgType === undefined || paramData.orgType === null) {
              paramData.orgType = -1
            }
            addDept(paramData)
              .then((response) => {
                this.$modal.msgSuccess('新增成功')
                this.open = false
                this.getList()
              })
              .catch((err) => {
                this.submitLoading = false
                console.error(err)
              })
          }
        } else {
          this.submitLoading = false
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除名称为"' + row.deptName + '"的数据项？')
        .then(function() {
          return delDept(row.deptId)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    renderOrgTypeByDeptId(deptId) {
      const dept = this.deptMap[deptId] || {}
      let result = ''
      this.form.orgType = ''
      if (dept) {
        const orgType = dept.orgType
        if (orgType >= 0 && this.orgTypeMap[orgType]) {
          result = this.orgTypeMap[orgType].label
          this.form.orgType = orgType
        }
      }
      return result
    },
    initDevisionParentsMap(result) {},
    initDeptDivisionCode(divisionCode) {
      this.divisionCodes = []
    }
  }
}
</script>
<style lang="scss" scoped>
.dept-dialog .el-select,
.dept-dialog .el-cascader {
  width: 100%;
}
</style>
